package com.atguigu.tingshu.common.config.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-02-25 14:36
 */
@Configuration
public class ThreadPoolConfig {


    /**
     * 线程数由应用类型决定,其中N指的是CPU核数（逻辑）： (大多数Java应用程序)IO密集型：2N+1     CPU密集型：N+1
     * 注册线程池对象
     * @return
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //1.获取可用CPU核数
        int count = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                count * 2,
                count * 2,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(200),
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy()  //拒绝任务执行，抛出异常
                //new ThreadPoolExecutor.DiscardPolicy()  //静默方式丢弃新提交任务
                //new ThreadPoolExecutor.DiscardOldestPolicy()  //静默方式丢弃等待时间最久的任务
                //new ThreadPoolExecutor.CallerRunsPolicy()  //调
                (r, e) -> {
                    //自定义拒绝策略  r:被拒绝任务对象  e:线程池对象
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                    //将任务再次提交给线程池尝试执行:确保任务被执行
                    e.submit(r);
                }
        );
        //2. 实例化线程池同时将核心线程创建  默认：第一个任务提交核心线程才创建
        threadPoolExecutor.prestartCoreThread();
        return threadPoolExecutor;
    }

}
